﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Shapes;
using Twi.COMMON.HTTP;
using System.Xml.Linq;

namespace Twi.COMMON.WPF
{
    /// <summary>
    /// Interaction logic for QueryCondition.xaml
    /// </summary>
    public partial class QueryConditionComponent : UserControl, IQueryConditionComponent
    {
        public QueryConditionComponent()
        {
            InitializeComponent();

            //不能直接在xaml界面定义事件, 因为是用户控件, 会提前触发事件
            //this.Loaded += new RoutedEventHandler(UserControl_Loaded);

            this.Date1.SelectedDate = SysDateTime.dateTime.AddDays(SysParam.DefaultStartDate);
            this.Date2.SelectedDate = SysDateTime.dateTime.AddDays(SysParam.DefaultEndDate);
            
            this.ChkDate.IsChecked = SysParam.DefaultIsCheck;
            this.ChkDate.IsEnabled = SysParam.DefaultIsEnable;

            this.TxtTextContent.TextChanged += new TextChangedEventHandler(TxtTextContent_TextChanged);
            this.TxtTextContent.PreviewMouseDown += new MouseButtonEventHandler(TxtTextContent_PreviewMouseDown);
            this.TxtTextContent.GotFocus += new RoutedEventHandler(TxtTextContent_GotFocus);
            this.TxtTextContent.LostFocus += new RoutedEventHandler(TxtTextContent_LostFocus);

            this.Date1.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(Date_SelectedDateChanged);
            this.Date2.SelectedDateChanged += new EventHandler<SelectionChangedEventArgs>(Date_SelectedDateChanged);
            this.CobDateComparison.SelectionChanged += new SelectionChangedEventHandler(CobDateComparison_SelectionChanged);

        }

        void TxtTextContent_LostFocus(object sender, RoutedEventArgs e)
        {
            TxtTextContent.PreviewMouseDown += new MouseButtonEventHandler(TxtTextContent_PreviewMouseDown);
        }

        void TxtTextContent_GotFocus(object sender, RoutedEventArgs e)
        {
            TxtTextContent.SelectAll();
            TxtTextContent.PreviewMouseDown -= new MouseButtonEventHandler(TxtTextContent_PreviewMouseDown);
        }

        void TxtTextContent_PreviewMouseDown(object sender, MouseButtonEventArgs e)
        {
            TxtTextContent.Focus();
            e.Handled = true;
        }

        private void CobDateComparison_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {
            if (CobDateComparison.SelectedIndex != -1)
            {
                if (CobDateComparison.SelectedValue.ToString() == "1")
                {
                    this.LblAnd.IsEnabled = true;
                    this.Date2.IsEnabled = true;
                }
                else
                {
                    this.LblAnd.IsEnabled = false;
                    this.Date2.IsEnabled = false;
                }
            }
        }

        public void SetTextContent(string txt)
        {
            this.TxtTextContent.Text = txt;
        }

        public void SetTextContentFocus()
        {
            this.TxtTextContent.Focus();
        }

        public void SetDateTime(DateTime dt1, DateTime? dt2)
        {
            if (dt1 != null)
            {
                Date1.SelectedDate = dt1;
            }
            if (dt2 != null)
            {
                Date2.SelectedDate = dt2;
            }
        }

        public void SetDefaultDateComparison(int index)
        {
            CobDateComparison.SelectedIndex = index;
        }

        //选择日期时触发
        void Date_SelectedDateChanged(object sender, SelectionChangedEventArgs e)
        {
            if (this.Date1.SelectedDate != null || this.Date2.SelectedDate != null)
                this.ChkDate.IsChecked = true;
            else
                this.ChkDate.IsChecked = false;
            e.Handled = true;
        }

        //输入文本时触发
        void TxtTextContent_TextChanged(object sender, TextChangedEventArgs e)
        {
            if (TxtTextContent.Text.Trim() != "")
                this.ChkText.IsChecked = true;
            else
                this.ChkText.IsChecked = false;
            e.Handled = true;
        }


        /// <summary>
        /// 检索条件，分成三种，0特殊处理，1统一处理，2模糊处理的SQL语句<Sql/>
        /// </summary>
        public XElement[] Conditions
        {
            get
            {
                List<XElement> condList = new List<XElement>();
                string sql = "";

                if (this.ChkText.IsChecked == true)
                {
                    #region 文本列
                    XElement xeSelectedTextCol = this.CobTextColName.SelectedItem as XElement;
                    string comparison = "";
                    string content = "";
                    content = this.TxtTextContent.Text.Trim().Replace("'", "").Replace("DELETE", "").Replace("UPDATE", "").Replace("INSERT", "");
                    string escape = "";
                    if (xeSelectedTextCol.Element("OperationType").GetValue(0) == 0)
                    {
                        switch (this.CobTextComparison.SelectedValue.ToString())
                        {
                            case "1":
                                comparison = "LIKE";
                                content = content.MaskWithWildcard();
                                escape = " ESCAPE '\\'";
                                break;
                            case "2":
                                comparison = "=";
                                break;
                            case "3":
                                comparison = "<>";
                                break;
                        }
                   
              
                        sql += string.Format(" AND {0} {1} '{2}'{3}", xeSelectedTextCol.Element("ColumnName").Value, comparison, content, escape);
                    }
                    else if (xeSelectedTextCol.Element("OperationType").GetValue(0) == 1)
                    {
                        condList.Add(new XElement(xeSelectedTextCol.Element("ColumnName").Value, content));
                    }
                    else
                    {
                        sql += string.Format(string.Format(" AND ({0}) ", xeSelectedTextCol.Element("ColumnName").Value), content);
                    }
                    #endregion
                }

                if (this.ChkDate.IsChecked == true)
                {
                    #region 日期列

                    string comparison = "";
                    string content = "";
                    switch (this.CobDateComparison.SelectedValue.ToString())//日期内容
                    {
                        case "1":
                            comparison = "BETWEEN";
                            content = string.Format("'{0:yyyy-MM-dd} 00:00:00' AND '{1:yyyy-MM-dd} 23:59:59'", this.Date1.SelectedDate, this.Date2.SelectedDate);
                            break;
                        case "2":
                            comparison = ">";
                            content = string.Format("'{0:yyyy-MM-dd} 00:00:00'", this.Date1.SelectedDate);
                            break;
                        case "3":
                            comparison = "<";
                            content = string.Format("'{0:yyyy-MM-dd} 23:59:59'", this.Date1.SelectedDate);
                            break;
                    }

                    XElement xeSelectedDateCol = this.CobDateColName.SelectedItem as XElement;
                    if (xeSelectedDateCol != null)
                    {
                        if (xeSelectedDateCol.Element("OperationType").Value == "0")
                        {
                            sql += string.Format(" AND {0} {1} {2}", xeSelectedDateCol.Element("ColumnName").Value, comparison, content);
                        }
                        else
                        {
                            condList.Add(new XElement(xeSelectedDateCol.Element("ColumnName").Value, comparison + " " + content));
                        }
                    }

                    #endregion
                }

                XElement xeSql = new XElement("Sql");
                xeSql.SetValue(sql);
                condList.Add(xeSql);
                return condList.ToArray();
            }
        }
        
        #region IQueryConditionComponent Members

        public TextBox GetTxtTextContent()
        {
            return TxtTextContent;
        }

        #endregion

        #region 清空选择框
        public void ClearChk()
        {
            this.ChkText.IsChecked = false;
            ChkDate.IsChecked = false;
        }
        #endregion

        #region 清空文本输入项选择框
        public void ClearChkText()
        {
            this.ChkText.IsChecked = false;
        }
        #endregion

        #region MenuCode属性定义
        public static readonly DependencyProperty MenuCodePropery = DependencyProperty.Register("MenuCode", typeof(string), typeof(QueryConditionComponent), new PropertyMetadata("", new PropertyChangedCallback(OnMenuCodeProperyChanged)));

        private static void OnMenuCodeProperyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            QueryConditionComponent uc = d as QueryConditionComponent;

            if (e.NewValue.ToString() != "" && Config.ServerAddress() != null)
            {
                //Visibility 是否显示0)显示;1)不显示且不保留空间(目前只用到0，2)
                using (HttpResponseMessage res = "QueryCondition/GetMultiple".HttpPost(new XElement("MenuCode", e.NewValue.ToString())
                    , new XElement("Visibility", 0)))
                {
                    ProcessRequest.Process(res, (ResponseMessageInfo resInfo) =>
                    {
                        uc.CobDateColName.ItemsSource = resInfo.ResponseDataMainBody.Elements().Where(x => x.Element("QueryDataType").Value == "1").OrderBy(x => int.Parse(x.Element("SortOrder").Value));
                        uc.CobTextColName.ItemsSource = resInfo.ResponseDataMainBody.Elements().Where(x => x.Element("QueryDataType").Value == "2").OrderBy(x => int.Parse(x.Element("SortOrder").Value));
                        
                        uc.CobDateColName.SelectedIndex = 0;
                        uc.CobTextColName.SelectedIndex = 0;
                    });
                }

                if (SysParam.FilterFuncCodeNoCheck != null && SysParam.FilterFuncCodeNoCheck.Contains(e.NewValue))
                {
                    uc.ChkDate.IsChecked = false;
                    uc.ChkDate.IsEnabled = true;
                }
            }
        }

        public string MenuCode
        {
            get { return GetValue(MenuCodePropery).ToString(); }
            set
            {
                SetValue(MenuCodePropery, value);

            }
        }
        #endregion 

        #region 文本检索条件属性定义
        public static readonly DependencyProperty TextComparisonVisibleProperty = DependencyProperty.Register("TextComparisonVisible", typeof(bool), typeof(QueryConditionComponent), new PropertyMetadata(true, new PropertyChangedCallback(OnTextComparisonVisibleProperyChanged)));

        private static void OnTextComparisonVisibleProperyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            QueryConditionComponent uc = d as QueryConditionComponent;

            if ((bool)e.NewValue == false)
            {
                uc.ColumnDefinTextComparison.Width = new GridLength(0);
                uc.CobTextComparison.Visibility = Visibility.Collapsed;
            }
        }

        public bool TextComparisonVisible
        {
            get { return (bool)GetValue(TextComparisonVisibleProperty); }
            set
            {
                SetValue(TextComparisonVisibleProperty, value);
            }
        }
        #endregion 

        #region 日期检索条件属性定义
        public static readonly DependencyProperty DateComparisonVisibleProperty = DependencyProperty.Register("DateComparisonVisible", typeof(bool), typeof(QueryConditionComponent), new PropertyMetadata(true, new PropertyChangedCallback(OnDateComparisonVisibleProperyChanged)));

        private static void OnDateComparisonVisibleProperyChanged(DependencyObject d, DependencyPropertyChangedEventArgs e)
        {
            QueryConditionComponent uc = d as QueryConditionComponent;

            if ((bool)e.NewValue == false)
            {
                uc.ColumnDefinDateComparison.Width = new GridLength(0);
                uc.CobDateComparison.Visibility = Visibility.Collapsed;
            }
        }

        public bool DateComparisonVisible
        {
            get { return (bool)GetValue(DateComparisonVisibleProperty); }
            set
            {
                SetValue(DateComparisonVisibleProperty, value);
            }
        }
        #endregion 

        #region 设置查询条件下拉选项
        /// <summary>
        /// 设置查询条件下拉选项
        /// </summary>
        /// <param name="columnName">字段名称</param>
        public void SetCobTextColNameIndex(string columnName)
        {
            try
            {
                var find = this.CobTextColName.Items.OfType<XElement>().Where(x => x.Element("ColumnName").GetValue().Trim().ToLower() == columnName.ToLower());
                if (find != null && find.Elements().Count() > 0)
                {
                    this.CobTextColName.SelectedItem = find.First();
                }
            }
            catch
            { 
            
            }
        }
        #endregion 
    }
}
